<template>
  <div class="child-component">
    <div class="flex justify-between items-center mb-5">
      <h3 class="m-0 text-lg font-semibold">子组件 (Child Component)</h3>
      <span class="badge">👶 Child</span>
    </div>

    <!-- 子组件生命周期状态 -->
    <div class="bg-white bg-opacity-10 p-4 rounded-md mb-4">
      <h4 class="text-yellow-300 mb-2 text-sm font-medium">子组件生命周期状态：</h4>
      <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
        <div
          v-for="status in childLifecycleStatus"
          :key="status.name"
          :class="['status-item', status.executed ? 'executed' : 'pending']"
        >
          {{ status.name }}: {{ status.executed ? '✅' : '⏳' }}
          <span v-if="status.time" class="text-xs opacity-80 ml-1">{{ status.time }}</span>
        </div>
      </div>
    </div>

    <!-- 从父组件接收的数据 -->
    <div class="bg-white bg-opacity-10 p-3 rounded-md mb-4">
      <h4 class="text-yellow-300 mb-2 text-sm font-medium">从父组件接收的Props：</h4>
      <p class="my-1 text-xs font-mono">计数器: {{ counter }}</p>
      <p class="my-1 text-xs font-mono">消息: {{ message }}</p>
    </div>

    <!-- 子组件自己的状态 -->
    <div class="bg-white bg-opacity-10 p-3 rounded-md mb-4">
      <h4 class="text-yellow-300 mb-2 text-sm font-medium">子组件内部状态：</h4>
      <p class="my-1 text-xs font-mono">更新次数: {{ childCounter }}</p>
      <p class="my-1 text-xs font-mono">孙组件消息: {{ childMessage }}</p>
    </div>

    <!-- 子组件控制按钮 -->
    <div class="flex gap-2 mb-4 flex-wrap">
      <button @click="updateChildState" class="child-btn">更新子组件状态</button>
      <button @click="emitToParent" class="child-btn">向父组件发送事件</button>
      <button @click="toggleGrandChild" class="child-btn">
        {{ showGrandChild ? '隐藏' : '显示' }}孙组件
      </button>
    </div>

    <!-- 孙组件 -->
    <div
      v-if="showGrandChild"
      class="mt-4 p-4 bg-white bg-opacity-5 rounded-md border border-dashed border-white border-opacity-30"
    >
      <GrandChildComponent :data="childCounter" @grandchild-event="handleGrandChildEvent" />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  computed,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  watch,
  nextTick,
} from 'vue'
import GrandChildComponent from './GrandChildComponent.vue'

// Props定义
interface Props {
  counter: number
  message: string
}

const props = defineProps<Props>()

// Emits定义
const emit = defineEmits<{
  childEvent: [data: { type: string; payload: any }]
}>()

// 子组件响应式数据
const childCounter = ref(0)
const childMessage = ref('等待孙组件消息...')
const showGrandChild = ref(false)

// 子组件生命周期状态追踪
const childLifecycleStatus = reactive([
  { name: 'setup', executed: true, time: new Date().toLocaleTimeString() },
  { name: 'onBeforeMount', executed: false, time: '' },
  { name: 'onMounted', executed: false, time: '' },
  { name: 'onBeforeUnmount', executed: false, time: '' },
  { name: 'onUnmounted', executed: false, time: '' },
])

// 计算属性
const computedValue = computed(() => {
  console.log('🧮 [Child] computed重新计算')
  return `计算值: ${props.counter * 2}`
})

// 辅助函数
const updateChildLifecycleStatus = (name: string) => {
  const status = childLifecycleStatus.find((s) => s.name === name)
  if (status) {
    status.executed = true
    status.time = new Date().toLocaleTimeString()
  }
}

const logChildLifecycle = (phase: string) => {
  console.log(`    🔹 [Child] ${phase} - ${new Date().toLocaleTimeString()}`)
}

// setup阶段
console.log('    🌱 [Child] setup开始 - 子组件实例创建')
logChildLifecycle('setup执行')

// 生命周期钩子
onBeforeMount(() => {
  logChildLifecycle('onBeforeMount - 子组件挂载前')
  updateChildLifecycleStatus('onBeforeMount')
})

onMounted(() => {
  logChildLifecycle('onMounted - 子组件挂载完成')
  updateChildLifecycleStatus('onMounted')
})

// 注意：onBeforeUpdate 和 onUpdated 会在任何响应式数据变化时触发
// 为避免无限循环，我们只在控制台记录，不更新页面状态
onBeforeUpdate(() => {
  logChildLifecycle('onBeforeUpdate - 子组件更新前')
  // 移除状态更新，避免无限循环：updateChildLifecycleStatus('onBeforeUpdate')
})

onUpdated(() => {
  logChildLifecycle('onUpdated - 子组件更新完成')
  // 移除状态更新，避免无限循环：updateChildLifecycleStatus('onUpdated')
})

onBeforeUnmount(() => {
  logChildLifecycle('onBeforeUnmount - 子组件卸载前')
  updateChildLifecycleStatus('onBeforeUnmount')
})

onUnmounted(() => {
  logChildLifecycle('onUnmounted - 子组件卸载完成')
  updateChildLifecycleStatus('onUnmounted')
})

// 监听Props变化
watch(
  () => props.counter,
  (newVal, oldVal) => {
    console.log(`    👀 [Child] watch props.counter: ${oldVal} -> ${newVal}`)
  },
)

watch(
  () => props.message,
  (newVal, oldVal) => {
    console.log(`    👀 [Child] watch props.message: ${oldVal} -> ${newVal}`)
  },
)

// 监听子组件自己的状态
watch(
  () => childCounter.value,
  (newVal, oldVal) => {
    console.log(`    👀 [Child] watch childCounter: ${oldVal} -> ${newVal}`)
  },
)

// 方法
const updateChildState = async () => {
  childCounter.value++
  // 不再更新消息，消息用来显示从孙组件接收到的数据
  logChildLifecycle(`触发第${childCounter.value}次状态更新`)

  await nextTick()
  console.log('    ✅ [Child] nextTick - 子组件DOM更新完成')
}

const emitToParent = () => {
  const eventData = {
    type: 'child-update',
    payload: {
      counter: childCounter.value,
      message: `子组件更新计数: ${childCounter.value}`,
      timestamp: new Date().toLocaleTimeString(),
    },
  }
  emit('childEvent', eventData)
  console.log('    📤 [Child] 向父组件发送事件:', eventData)
}

const toggleGrandChild = () => {
  showGrandChild.value = !showGrandChild.value
  logChildLifecycle(`${showGrandChild.value ? '显示' : '隐藏'}孙组件`)
}

const handleGrandChildEvent = (data: any) => {
  console.log('    📨 [Child] 接收到孙组件事件:', data)
  // 更新消息字段来显示从孙组件接收到的消息
  childMessage.value = `来自孙组件: 状态${data.payload.state} (${data.payload.timestamp})`
}

console.log('    ✅ [Child] 子组件setup完成')
</script>

<style scoped lang="scss">
// 复杂渐变背景用sass实现
.child-component {
  @apply rounded-lg p-5 text-white border-2 border-white border-opacity-30;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

// 徽章样式
.badge {
  @apply px-3 py-1 rounded-2xl text-xs font-bold;
  background: rgba(255, 255, 255, 0.2);
}

// 警告提示框样式用sass实现
.update-note {
  @apply rounded p-2 mb-2;
  background: rgba(255, 193, 7, 0.15);
  border: 1px solid rgba(255, 193, 7, 0.3);
}

// 状态项样式
.status-item {
  @apply p-2 rounded text-xs transition-all duration-300;

  &.pending {
    @apply bg-white bg-opacity-10;
    border-left: 3px solid #ff9800;
  }

  &.executed {
    background: rgba(76, 175, 80, 0.2);
    border-left: 3px solid #4caf50;
  }
}

// 子组件按钮样式
.child-btn {
  @apply px-4 py-2 rounded-2xl text-white cursor-pointer transition-all duration-300 text-xs;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);

  &:hover {
    background: rgba(255, 255, 255, 0.3);
    transform: scale(1.05);
  }
}
</style>
